package cn.jekun.shop.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.NotBlank;
import cn.jekun.component.base.validator.annotation.Num;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpCoupon;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.bean.gen.TsAccount;
import cn.jekun.component.core.bean.gen.TsOperationCode;
import cn.jekun.component.core.service.AccountPayService;
import cn.jekun.component.core.service.gen.ErpCouponService;
import cn.jekun.shop.common.service.AccountService;
import cn.jekun.shop.common.service.ShopBaseAction;
import cn.jekun.shop.web.bean.ShopAccounts;


/**
 * 账户信息查询
 * 
 * @author Mr.Dong
 *
 */
@SuppressWarnings("serial")
public class AccountAction extends ShopBaseAction {
	
	@Resource(name= ErpCouponService.BEAN_NAME)
	private ErpCouponService erpCouponService;
	
	private static final String AUTH_SHOP_MY_SECURITY="SHOP_MY_SECURITY";//安全设置
	private List<TsOperationCode> resultOperCodeList = new ArrayList<TsOperationCode>();
	private List<ShopAccounts> resultQueryDateList = new ArrayList<ShopAccounts>();
	private ShopAccounts shopAccounts;
	public ShopAccounts getShopAccounts() {
		return shopAccounts;
	}
	public void setShopAccounts(ShopAccounts shopAccounts) {
		this.shopAccounts = shopAccounts;
	}
	public List<ShopAccounts> getResultQueryDateList() {
		return resultQueryDateList;
	}
	public void setResultQueryDateList(List<ShopAccounts> resultQueryDateList) {
		this.resultQueryDateList = resultQueryDateList;
	}
	private String queryDate; //日期查询条件 
	private String operType;  //账户流水类型
	private String beginMoney; //开始金额
	private String endMoney;   //结束金额
	private String beginDate;  //开始日期
	private String endDate;    //结束日期
	private String search_date;
	public String getSearch_date() {
		return search_date;
	}
	public void setSearch_date(String search_date) {
		this.search_date = search_date;
	}
	public String getBeginDate() {
		return beginDate;
	}
	public void setBeginDate(String beginDate) {
		this.beginDate = beginDate;
	}
	public String getEndDate() {
		return endDate;
	}
	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}
	private String keyRange;   //关键词
	private String keyword_s;  //关键词查询条件
	public String getQueryDate() {
		return queryDate;
	}
	public void setQueryDate(String queryDate) {
		this.queryDate = queryDate;
	}
	public String getOperType() {
		return operType;
	}
	public void setOperType(String operType) {
		this.operType = operType;
	}
	public String getBeginMoney() {
		return beginMoney;
	}
	public void setBeginMoney(String beginMoney) {
		this.beginMoney = beginMoney;
	}
	public String getEndMoney() {
		return endMoney;
	}
	public void setEndMoney(String endMoney) {
		this.endMoney = endMoney;
	}
	public String getKeyRange() {
		return keyRange;
	}
	public void setKeyRange(String keyRange) {
		this.keyRange = keyRange;
	}
	public String getKeyword_s() {
		return keyword_s;
	}
	public void setKeyword_s(String keyword_s) {
		this.keyword_s = keyword_s;
	}
	public List<TsOperationCode> getResultOperCodeList() {
		return resultOperCodeList;
	}
	public void setResultOperCodeList(List<TsOperationCode> resultOperCodeList) {
		this.resultOperCodeList = resultOperCodeList;
	}

	public AccountService getAccountService() {
		return accountService;
	}
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}
	@Resource(name=AccountService.BEAN_NAME)
	AccountService accountService;
	
	private TsAccount tsAccount;
	

	public TsAccount getTsAccount() {
		return tsAccount;
	}
	public void setTsAccount(TsAccount tsAccount) {
		this.tsAccount = tsAccount;
	}
	@Resource(name = AccountPayService.BEAN_NAME)
	AccountPayService accountPayService;
	public String getAccountDetails(){
		
		JSONObject jsonObject=new JSONObject();
		
		String pageSize = this.request.getParameter("pageSize");
		String currentPage = this.request.getParameter("currentPage");
		String queryDate = this.request.getParameter("queryDate");
		String operationCode = this.request.getParameter("operationCode");
		String userId=this.getSessionUser().getUserId();//this.getSessionUser().getShopId();
		
		try {
			jsonObject = this.accountService.getAccountDetails(queryDate,operationCode,"","","",
					"","",
					"",userId,pageSize, currentPage);
			this.resultQueryDateList = this.accountService.getQueryDate(queryDate);
			request.setAttribute("beginDate",resultQueryDateList.get(0).getBeginDate()==null?
					"":resultQueryDateList.get(0).getBeginDate().toString());
			request.setAttribute("endDate",resultQueryDateList.get(0).getEndDate()==null?
					"":resultQueryDateList.get(0).getEndDate().toString());	
			if(search_date!=null && "true".equals(search_date.trim())){
				request.setAttribute("beginDate",beginDate);
				request.setAttribute("endDate",endDate);
			}
			TsAccount tempBalance = this.accountService.one(userId);
			java.text.NumberFormat nf = java.text.NumberFormat.getInstance();   
			nf.setGroupingUsed(false); 
			String balance="";
			if(tempBalance==null){
				balance="0";
			}else{
				balance=nf.format(tempBalance.getBalance());
			}
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

			jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());
			
			jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());
			
			jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
			
			jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());
			
			jsonObject.put("balance", balance);

		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
			
		
		return this.writeJson(jsonObject);
		
		
		
		

	}
	/**
	 * 获取提现流水详情
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String getAccountDetailsById(){
		
//	 Map map = new HashMap();
//	 map.put("accountJourId", request.getParameter("accountJourId"));
//	 this.shopAccounts = accountService.getAccountDetailsById(map);
//	 
//	 return "/shop/accounttrandetails.jsp";
	 
	 
	 JSONObject jsonObject=new JSONObject();
		
		try {
			String accountJourId=request.getParameter("accountJourId");
			 this.shopAccounts = accountService.getAccountDetailsById(accountJourId);
			 
				if(shopAccounts!=null){
					jsonObject.put("applystautusId",shopAccounts.getApplyStatusId()==null?"":shopAccounts.getApplyStatusId());
					jsonObject.put("applystautusname",shopAccounts.getApplyStatusName()==null?"":shopAccounts.getApplyStatusName());
					jsonObject.put("settleResultId",shopAccounts.getSettleResultId()==null?"":shopAccounts.getSettleResultId());
					jsonObject.put("settleresult",shopAccounts.getSettleResult()==null?"":shopAccounts.getSettleResult());
					jsonObject.put("accountJourId",shopAccounts.getAccountJourId()==null?"":shopAccounts.getAccountJourId());
					jsonObject.put("accountId",shopAccounts.getAccountId()==null?"":shopAccounts.getAccountId());
					jsonObject.put("applyCommitTime",shopAccounts.getApplycommitTime()==null?"":shopAccounts.getApplycommitTime());
					jsonObject.put("amount",shopAccounts.getAmount()==null?"":shopAccounts.getAmount());
					jsonObject.put("fee",shopAccounts.getFee()==null?"":shopAccounts.getFee());
					jsonObject.put("applyTypeName",shopAccounts.getApplyTypeName()==null?"":shopAccounts.getApplyTypeName());
					jsonObject.put("reqBankTime",shopAccounts.getReqBankTime()==null?"":shopAccounts.getReqBankTime());
					jsonObject.put("operationName",shopAccounts.getOperationName()==null?"":shopAccounts.getOperationName());
					jsonObject.put("finishBankTime",shopAccounts.getFinishBankTime()==null?"":shopAccounts.getFinishBankTime());
				}
				
				
				
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
				
				
			
			
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		
		return this.writeJson(jsonObject);
	 
	 
	 
	}
	
	
	
	
	/**
	 * 获取流水类型
	 * @return
	 */
	public String queryOperType(){
		
		JSONObject jsonObject=new JSONObject();
		
		
		try {
			this.resultOperCodeList = this.accountService.getOperTypes();
			
			JSONArray jsonArray = new JSONArray();
			
			HashMap<String, Object> hashMap;
			
			for(int i=0;i<this.resultOperCodeList.size();i++){
				
			
				TsOperationCode tempTsOperationCode=(TsOperationCode) resultOperCodeList.get(i);
				
				hashMap=new HashMap<String, Object>();
				
				hashMap.put(TsOperationCode.COL_OPERATION_CODE, tempTsOperationCode.getOperationCode());
				
				hashMap.put(TsOperationCode.COL_OPERATION, tempTsOperationCode.getOperation());
				
				jsonArray.add(hashMap);
				
			}
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

			jsonObject.put("operTypeListData", jsonArray);
			
			
			
		}  catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		
		return this.writeJson(jsonObject);
	}
	
	
	/**
	 * 个人备付金账户
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String queryAccount(){
	
		
		JSONObject jsonObject=new JSONObject();
		
		try{
			String userId=this.getSessionUser().getUserId();
			HashMap map = accountService.getTsAccount(userId,Constants.TS_ACCOUNT_OWNER_TYPE.SHOP);
				
			if(map!=null){
				
				jsonObject.put("ACCOUNT_ID", map.get("ACCOUNT_ID"));
				
				jsonObject.put("BALANCE", map.get("BALANCE"));
					
				jsonObject.put("USER_ID", map.get("USER_ID")==null?"":map.get("USER_ID"));
					
				jsonObject.put("USER_NAME", map.get("USER_NAME"));
					
				jsonObject.put("CREATE_TIME", map.get("CREATE_TIME"));
				
				jsonObject.put("STATUS_ID", map.get("STATUS_ID"));
				
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

				jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
				
			}else{
				
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

				jsonObject.put(ErrorMsg.KEY_MESSAGE,"-1");
				
			}
			
			
			
		}catch(Exception e){
			
			
			e.printStackTrace();
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);

			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
		}
		
		
		return this.writeJson(jsonObject);
	}
	
	
	/**
	 * 绑定备付金账户
	 * @return
	 */
	public String addUserAccount(){
		
		JSONObject jsonObject=new JSONObject();
		
		try{
		Map map = new HashMap();
//		map.put("tsAccount", tsAccount);
		tsAccount.setOwnerId(this.getSessionUser().getUserId());
		tsAccount.setAccountTypeId("1");
		tsAccount.setOwnerTypeId(Constants.TS_ACCOUNT_OWNER_TYPE.SHOP);
		tsAccount.setBalance(tsAccount.getBalance()==null?Double.parseDouble("0.00"):tsAccount.getBalance());
		tsAccount.setPassword(tsAccount.getPassword());
//		tsAccountService.insert(map);
		//shopsService.insertAccount(tsAccount);
		
		accountPayService.create(tsAccount.getOwnerId(), tsAccount.getOwnerTypeId(), tsAccount.getPassword(), tsAccount.getSignType(), tsAccount.getBalance()+"","");
		
		//this.saveActionMessage("绑定备付金账户成功！");
		//this.logService.addAdminAuditLog("", "绑定备付金账户成功,商家代码:"+tsAccount.getOwnerId());//记录操作日志
		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

		jsonObject.put(ErrorMsg.KEY_MESSAGE,"绑定备付金账户成功");
		
		
		}catch(Exception e){
			
			
			e.printStackTrace();
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);

			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
		}
		
		
		return this.writeJson(jsonObject);
		
	}
	
	/**
	 * 账户激活
	 * /core/Account/activate.do
	 * @return
	 */
	public String activate(){
		JSONObject jsonObject = null;
		try {
			String terminalId="";

			String ownerId=this.getSessionUser().getUserId();
			String password=this.request.getParameter("password");
			String ownerType=Constants.TS_ACCOUNT_OWNER_TYPE.SHOP;
//			this.validateSign(getLoginSign(),ownerId,getUserId());//验证签名是否正确 md5(loginSign +ownerId+ userId)
//			this.validateLoginApp();//验证是否登录
			jsonObject=accountPayService.activate(terminalId, ownerId,ownerType,password);
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

			jsonObject.put(ErrorMsg.KEY_MESSAGE,"激活成功");
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);

			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
		}
		return this.writeJson(jsonObject);// 输出
	}

	/**
	 * BOX-73 BOX-74
	 * 支付时查看我的优惠券使用优惠券支付接口
	 * 支付时查看我的账户可支付余额使用余额支付接口
	 * @return
	 */
	public String getAccountInfo(){
		JSONObject jsonObject=new JSONObject();
		
		try {
			//String shopId;
			//this.validateLoginApp(); 
			//this.validateSign(this.getLoginSign(),this.getUserId());
			
			JSONObject jsonAccountObject=accountPayService.querySettleAmount("", this.getUserId(),Constants.TS_ACCOUNT_OWNER_TYPE.USER);
			String code=jsonAccountObject.getString("code");
			if(code.equals("1")){
				String amountCount=jsonAccountObject.getString("balance");//可提现
				Double balanceAmount=new Double(amountCount);
				
				String settleAmount=jsonAccountObject.getString("settleAmount");//可支付余额
				Double settleAmountDouble=new Double(settleAmount);
				

				java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
				nf.setGroupingUsed(false); 
				nf.setMinimumFractionDigits(3);
				
				jsonObject.put("balance",settleAmountDouble==null?"":nf.format(settleAmountDouble)) ;//可提现
				//jsonObject.put("amount",amountDouble);//余额
			}else{
				//jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				//jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有找到支付账户。");
				//return this.writeJson(jsonObject);
				jsonObject.put("balance",0) ;//可提现
				//jsonObject.put("amount",0);//余额
			}
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

			//获取用户有效的优惠券
			Map couponMap = new HashMap();
			couponMap.put(ErpCoupon.COL_USER_ID, this.getUserId());
			couponMap.put(ErpCoupon.COL_AVAILABLE, "1");
			SqlUtis.prepareSql(couponMap
					,SqlUtis.getSQL(couponMap, ErpCoupon.COL_USER_ID)
					,SqlUtis.getSQL(couponMap, ErpCoupon.COL_AVAILABLE)
					," and (a.start_time is null or (a.start_time is not null and sysdate >= a.start_time) ) and (a.end_time is null or (a.end_time is not null and sysdate <= a.end_time) )"
					,SqlUtis.orderBy(ErpCoupon.COL_CREATE_TIME)
					);
			List<ErpCoupon> coupons = this.erpCouponService.list(couponMap);
			jsonObject.put("coupons", JSONArray.fromObject(coupons));
			//end
			
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
			
		
		return this.writeJson(jsonObject);
		
	}
	
}
